package logic

import (
	"context"
	"encoding/json"
	"sport/models/mysql"
	"sport/models/redis"
	"time"

	"sport/sportrpc/internal/svc"
	"sport/sportrpc/sportrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type HotLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewHotLogic(ctx context.Context, svcCtx *svc.ServiceContext) *HotLogic {
	return &HotLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 热度展示
func (l *HotLogic) Hot(in *sportrpc.HotRequest) (*sportrpc.HotResponse, error) {
	// todo: add your logic here and delete this line
	var post []mysql.Post
	get := redis.Rdb.Get(l.ctx, "hot")
	if get.Val() == "" {
		mysql.DB.Order("Liked desc").Limit(10).Find(&post)
		marshal, _ := json.Marshal(post)
		redis.Rdb.Set(l.ctx, "hot", marshal, time.Minute*5)
	} else {
		json.Unmarshal([]byte(get.Val()), &post)
	}
	var posts []*sportrpc.Listhot
	for _, m := range post {
		list := sportrpc.Listhot{
			UserId:  int64(m.UserId),
			ForumId: int64(m.ForumId),
			Title:   m.Title,
			Content: m.Content,
			Liked:   int64(m.Liked),
		}
		posts = append(posts, &list)
	}
	return &sportrpc.HotResponse{
		List: posts,
	}, nil
}
